<?php

namespace App\Kuafu\User\Service;

use App\Console\Commands\Feishu\SynchronizeUserinfo;
use App\Exceptions\BaseException;
use App\Kuafu\Base\Service\BaseService;
use App\Kuafu\Config\Service\ConfigService;
use App\Kuafu\Feishu\Model\FsUserModel;
use App\Kuafu\Nsq\Enum\NsqCodeEnum;
use App\Library\FeiShu\SendFs;
use Kuafu\GeneralFs\BuildFs;
use Kuafu\Nsq\NsqPublisher;

class FsUserService extends BaseService
{
    const NOTIFY_TYPE_KF_MERCHANT = "KF_MERCHANT";
    const NOTIFY_TYPE_KF_KMS      = "KF_KMS";
    const NOTIFY_TYPE_TEXT        = [
        self::NOTIFY_TYPE_KF_MERCHANT => "夸父商家",
        self::NOTIFY_TYPE_KF_KMS      => "夸父运营",
    ];

    public static function lists(string $departmentName, string $rootDepartmentId, array $fields = ['*'])
    {
        return FsUserModel::query()
                          ->when($departmentName, function ($query) use ($departmentName) {
                              $query->where('departmentName', 'like', "%{$departmentName}%");
                          })
                          ->when($rootDepartmentId, function ($query) use ($rootDepartmentId) {
                              $query->where('rootDepartmentId', $rootDepartmentId);
                          })
                          ->where('isResigned', 0)
                          ->select($fields)
                          ->get();
    }


    /**
     * @param object $params
     * @return array|false|string|void
     * @throws BaseException
     */
    public static function notify(object $params)
    {
        try {
            $config        = ConfigService::getConfigDetail("fsUser", "fsNotifyConfig")["value"];
            $configCollect = collect($config);
            $configDetail  = $configCollect->where("type", $params->type)->first();
            $encryptKey    = $configDetail["encryptKey"];
            $token         = $configDetail["token"];

            $base64_decode_message = base64_decode($params->encrypt);
            $iv                    = substr($base64_decode_message, 0, 16);
            $encryptedEvent        = substr($base64_decode_message, 16);
            $decryptStr            = openssl_decrypt(
                $encryptedEvent,
                'AES-256-CBC',
                hash('sha256', $encryptKey, true),
                OPENSSL_RAW_DATA,
                $iv
            );

            logMsg(
                "[飞书事件订阅日志]-[加解密数据集]",
                [
                    "encrypt" => $params->encrypt,
                    "decrypt" => jsonToArr($decryptStr, $decryptStr)
                ],
                true,
                false
            );

            if (!$decryptStr) {
                throw new \Exception("数据解密失败 [{$params->encrypt}]");
            }

            $decrypt = json_decode($decryptStr, true);
            if (attributeGet($decrypt, "challenge", null)) {
                return $decrypt;
            }

//            if (attributeGet($decrypt, "header.token", null) != $token) {
//                throw new \Exception("请求来源非法 [{$params->encrypt}]");
//            }

            // nsq 推送飞书订阅消息
            (new NsqPublisher(config('nsq.default.address')))->pub(NsqCodeEnum::FS_EVENT, $decrypt);

            $exitedUser = '';

            $eventType = attributeGet($decrypt, "header.event_type", null);
            switch ($eventType) {
                case "contact.user.deleted_v3":
                    $fsUserId    = attributeGet($decrypt, "event.object.user_id", null);
                    $fsUserGroup = FsUserModel::query()->where("userId", $fsUserId)->where("isExited", 0)->get();
                    if ($fsUserGroup->isNotEmpty()) {
                        $fsUserGroup->each(function (FsUserModel $fsUserModel) {
                            $fsUserModel->isExited     = 1;
                            $fsUserModel->isResigned   = 1;
                            $fsUserModel->resignedTime = time();
                            $fsUserModel->save();
                        });

                        $exitedUser .= SynchronizeUserinfo::stopUser($fsUserGroup->first());

                        logMsg(
                            "飞书人员变动离职通知",
                            attributeGet($decrypt, "event.object", []),
                            true,
                            false
                        );
                    }
                    break;
//                case 'contact.user.created_v3':
//                    $fsUserId    = attributeGet($decrypt, "event.object.user_id", null);
//                    break;
            }

            if ($exitedUser) {
                BuildFs::newRobot(SendFs::ROBOT_BUSINESS_WARING)
                       ->setTitleContent('用户账号被停用', $exitedUser)
                       ->setAtUid('e119e19f')
                       ->send();
            }

            return [];
        } catch (\Exception $exception) {
            handleException($exception, $exception->getMessage());
        }
    }
}
